package com.uft.model.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.uft.model.entity.Preferences;
import com.uft.model.entity.Profile;


@Repository
public class PreferencesDAO {
	@PersistenceContext private EntityManager em;
	
	public List<Preferences> getAllPreferences() {
	       TypedQuery<Preferences> query = em.createQuery(
	           "SELECT p FROM Preferences p ", Preferences.class);
	       return query.getResultList();
	}
	public Preferences getPreferencesByName(String prefName){
		try{
			 return  (Preferences) em.createNamedQuery("getPreferencesByName")
					    .setParameter("prefName", prefName)
					    .getSingleResult();
		}catch(NoResultException e){
			return null;
		}
		
	}
	public Preferences getPreferencesByCategoryName(String category, String prefName){
		try{
			return  (Preferences) em.createNamedQuery("getPreferencesByCategoryName")
				    .setParameter("prefName", prefName)
				    .setParameter("category", category)
				    .getSingleResult();
		}catch(NoResultException e){
			return null;
		}
		 
	}
	public List<Preferences> getPreferencesByCategory(String c) {
		// TODO Auto-generated method stub
		TypedQuery<Preferences> query = em.createQuery(
		           "SELECT p FROM Preferences p where p.prefCategory='"+c+"'", Preferences.class);
		       return query.getResultList();

	}
	
	public List<String> getDistinctCategoryName(){
		try{
			return  (List<String>) em.createNamedQuery("getDistinctCategoryName").getResultList();
		}catch(NoResultException e){
			return null;
		}
	}
	@Transactional
	public void addPreferences(Preferences pref){
	   System.out.println("Preference Name : "+pref.getPrefName());
	   em.persist(pref);
	   System.out.println("Preference id: "+pref.getPreferenceId());
	}
	
	@Transactional
	public void deletePreferencesById(int  PreferenceId) {
		// TODO Auto-generated method stub
		   System.out.println("Preference id: "+PreferenceId);
		   Preferences preference = em.find(Preferences.class, PreferenceId);
		   em.remove(preference);
		   
	   }
	@Transactional
	public void updatePreferences(Preferences pref) {
		// TODO Auto-generated method stub
		System.out.println("Preference Name : "+pref.getPrefName());
		em.merge(pref);
		System.out.println("Preference id: "+pref.getPreferenceId());
		
	}
	
}
